package com.cwh.taskcenter.domain.notice.factory;

import com.cwh.taskcenter.domain.notice.strategy.NotificationStrategy;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Component;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * 通知策略工厂
 * 负责创建和管理各种通知渠道的策略实例
 */
@Component
public class NotificationStrategyFactory {

    private final Map<String, NotificationStrategy> strategies = new ConcurrentHashMap<>();

    @Autowired
    public NotificationStrategyFactory(ApplicationContext context) {
        Map<String, NotificationStrategy> beans = context.getBeansOfType(NotificationStrategy.class);
        for (Map.Entry<String, NotificationStrategy> entry : beans.entrySet()) {
            String strategyKey = extractStrategyKey(entry.getKey());
            strategies.put(strategyKey, entry.getValue());
        }
    }

    /**
     * 提取策略键值
     * 将类似 "SmsNotificationStrategy" 的字符串转换为 "SMS"
     */
    private String extractStrategyKey(String beanName) {
        if (beanName.endsWith("NotificationStrategy")) {
            return beanName.replace("NotificationStrategy", "").toUpperCase();
        }
        return beanName.toUpperCase();
    }

    /**
     * 获取指定类型的通知策略
     * @param channelType 渠道类型
     * @return NotificationStrategy 通知策略
     * @throws IllegalArgumentException 如果没有找到匹配的策略
     */
    public NotificationStrategy getStrategy(String channelType) {
        if (channelType == null || channelType.isEmpty()) {
            throw new IllegalArgumentException("渠道类型不能为空");
        }

        NotificationStrategy strategy = strategies.get(channelType.toUpperCase());
        if (strategy == null) {
            throw new IllegalArgumentException("不支持的通知渠道: " + channelType);
        }
        return strategy;
    }
}
